package com.renwei.yunlong.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.LoginBean;
import com.renwei.yunlong.bean.RegisterBean;
import com.renwei.yunlong.http.HttpPresenter;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.ACache;
import com.renwei.yunlong.utils.ToastUtil;
import com.zyf.fwms.commonlibrary.http.Api;
import com.zyf.fwms.commonlibrary.utils.AutoUtils;
import com.zyf.fwms.commonlibrary.utils.CommonUtils;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

import static android.R.attr.breadCrumbShortTitle;
import static android.R.attr.cacheColorHint;
import static android.R.attr.password;

/**
 * 注册页面
 * <p>
 * Created by Administrator on 2017/8/22.
 */

public class RegisterActivity extends BaseActivity implements View.OnClickListener, HttpTaskListener{

    @Bind(R.id.iv_back)
    ImageView ivBack;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_protocol)
    TextView tvProtocol;
    @Bind(R.id.iv_service)
    ImageView ivService;
    @Bind(R.id.tv_service)
    TextView tvService;
    @Bind(R.id.rl_service)
    RelativeLayout rlService;
    @Bind(R.id.iv_owner)
    ImageView ivOwner;
    @Bind(R.id.tv_owner)
    TextView tvOwner;
    @Bind(R.id.rl_owner)
    RelativeLayout rlOwner;

    static Button btnVercode;
    @Bind(R.id.et_name)
    EditText etName;//姓名
    @Bind(R.id.et_phone)
    EditText etPhone;//手机号
    @Bind(R.id.et_verification)
    EditText etVerification;//验证码
    @Bind(R.id.et_pwd)
    EditText etPwd;//密码
    @Bind(R.id.et_determine_pwd)
    EditText etDeterminePwd;//确认密码
    @Bind(R.id.et_enterprise)
    EditText etEnterprise;//企业名称
    @Bind(R.id.btn_register)
    Button btnRegister;//注册按钮

    @Bind(R.id.iv_protocol_check)
    ImageView ivProtocolCheck;

    private HttpPresenter hp;//网络
    private ACache mCache;

    Map<String ,String> map=new HashMap<String, String>();

    private RegisterHandler myHandler = new RegisterHandler(this);

    private String companyTypeStr = "2";//企业类型

    private String userName;
    private String password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        mCache = ACache.get(this);

        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);
        //屏幕自适配
        AutoUtils.setSize(this, false, 720, 1280);
        AutoUtils.auto(this);

        initData();
    }

    private void initData() {
        btnVercode = (Button) findViewById(R.id.btn_vercode);

        tvTitle.setText("注册");
        ivBack.setVisibility(View.VISIBLE);
        ivBack.setOnClickListener(this);
        tvProtocol.setOnClickListener(this);
        rlService.setOnClickListener(this);
        rlOwner.setOnClickListener(this);

        ivProtocolCheck.setOnClickListener(this);//协议

        btnVercode.setOnClickListener(this);
        btnRegister.setOnClickListener(this);

        TextChange textChange  = new TextChange();
        etEnterprise.addTextChangedListener(textChange);
        etName.addTextChangedListener(textChange);
        etPhone.addTextChangedListener(textChange);
        etVerification.addTextChangedListener(textChange);
        etPwd.addTextChangedListener(textChange);
        etDeterminePwd.addTextChangedListener(textChange);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_protocol:
                startActivity(new Intent(this, ProtocolActivity.class));
                break;
            case R.id.iv_protocol_check://协议勾选
                ivProtocolCheck.setImageResource(R.mipmap.check02);
                break;
            case R.id.rl_service://服务商

                companyTypeStr = "2";//标记号

                ivService.setImageResource(R.mipmap.service01);
                tvService.setTextColor(getResources().getColor(R.color.blue_color));
                ivOwner.setImageResource(R.mipmap.owner02);
                tvOwner.setTextColor(getResources().getColor(R.color.text_dark_gray_color));
                break;
            case R.id.rl_owner://业主

                companyTypeStr = "1";//标记号

                ivOwner.setImageResource(R.mipmap.owner01);
                tvOwner.setTextColor(getResources().getColor(R.color.blue_color));
                ivService.setImageResource(R.mipmap.service02);
                tvService.setTextColor(getResources().getColor(R.color.text_dark_gray_color));
                break;
            case R.id.btn_vercode:
                String phone = etPhone.getText().toString().trim();
                if (!TextUtils.isEmpty(phone)) {
                    middleRegisterVercodeHttp(phone);
                    sendMessageClick();//发送验证码
                }
                break;
            case R.id.btn_register:
                String enterpriseName = etEnterprise.getText().toString().trim();
                String Name = etName.getText().toString().trim();
                String mobilePhone = etPhone.getText().toString().trim();
                String vercode = etVerification.getText().toString().trim();
                String determinePwd = etDeterminePwd.getText().toString().trim();

                String jsonBean="{companyName:\""+enterpriseName+"\",name:\""+Name+"\",mobilePhone:\""+mobilePhone+"\",password:\""+determinePwd+"\",vercode:\""+vercode+"\",companyType:\""+companyTypeStr+"\"}";

                if ("1".equals(companyTypeStr)){
                    ownerRegisterHttp(jsonBean);//业主
                }else {
                    serviceRegisterHttp(jsonBean);//服务商
                }
                userName = mobilePhone;
                password = determinePwd;

                break;
            default:
                break;
        }
    }

    //业主注册
    private void ownerRegisterHttp(String jsonBean) {
        hp = new HttpPresenter(RegisterActivity.this);
        hp.setUrl(Api.MiDDLE_REGISTER_URL);
        hp.setShowDialog(false);
        hp.setRequsetId(2);
        hp.putParam("jsonBean",jsonBean);
        hp.setCallBack(this);
        hp.post();
    }

    //服务商注册
    private void serviceRegisterHttp(String jsonBean) {
        hp = new HttpPresenter(RegisterActivity.this);
        hp.setUrl(Api.MiDDLE_REGISTER_URL);
        hp.setShowDialog(false);
        hp.setRequsetId(3);
        hp.putParam("jsonBean",jsonBean);
        hp.setCallBack(this);
        hp.post();
    }

    //中间发送验证码
    private void middleRegisterVercodeHttp(String mobilePhone) {
        hp = new HttpPresenter(RegisterActivity.this);
        hp.setUrl("http://106.14.20.156:8083/MiddleServer/sendVercode.htm");
        hp.setShowDialog(false);
        hp.setRequsetId(1);
        hp.putParam("mobilePhone", mobilePhone);
        hp.setCallBack(this);
        hp.post();
    }

    //业主登录
    private void ownerLoginHttp(String jsonBean) {
        HttpPresenter hp = new HttpPresenter(RegisterActivity.this);
        hp.setUrl(Api.OWNER_LOGIN_URL);
        hp.setshowDialogcontent("正在注册并登录");
        hp.setRequsetId(4);
        hp.putParam("jsonBean",jsonBean);
        hp.setCallBack(this);
        hp.post();
    }

    //服务商登录
    private void serviceLoginHttp(String jsonBean) {
        HttpPresenter hp = new HttpPresenter(RegisterActivity.this);
        hp.setUrl(Api.SERVICE_LOGIN_URL);
        hp.setshowDialogcontent("正在注册并登录");
        hp.setRequsetId(5);
        hp.putParam("jsonBean",jsonBean);
        hp.setCallBack(this);
        hp.post();
    }

    /**
     * 网络请求回调
     *
     * @param requestId
     * @param result
     */
    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 1:
                break;
            case 2:
                String jsonBean="{userName:\""+userName+"\",password:\""+password+"\"}";
                RegisterBean registerBean = new Gson().fromJson(result, RegisterBean.class);

                if (registerBean.getMessage().getCode() == 200){//成功  200
                    ownerLoginHttp(jsonBean);
                }else if (registerBean.getMessage().getCode() == 201){//手机验证码错误
                    ToastUtil.showShort(this,"手机验证码错误");

                }else if (registerBean.getMessage().getCode() == 1001){//手机号已被注册
                    ToastUtil.showShort(this,"手机号已被注册");
                }else {//企业名称已被注册
                    ToastUtil.showShort(this,"企业名称已被注册");
                }
                break;
            case 3:
                Toast.makeText(RegisterActivity.this,result.toString(),Toast.LENGTH_SHORT).show();
                Log.e("服务商注册返回",result);

                jsonBean="{userName:\""+userName+"\",password:\""+password+"\"}";

                Log.e("服务商注册jsonBean",userName+"---"+password);

                registerBean = new Gson().fromJson(result, RegisterBean.class);
                if (registerBean.getMessage().getCode() == 200){//成功  200
                    ToastUtil.showShort(this,"成功");
                    serviceLoginHttp(jsonBean);

                }else if (registerBean.getMessage().getCode() == 201){//手机验证码错误
                    ToastUtil.showShort(this,"手机验证码错误");
                }else if (registerBean.getMessage().getCode() == 1001){//手机号已被注册
                    ToastUtil.showShort(this,"手机号已被注册");
                }else {//企业名称已被注册
                    ToastUtil.showShort(this,"企业名称已被注册");
                }

                break;
            case 4:
                LoginBean loginBean = new Gson().fromJson(result,LoginBean.class);

                if (loginBean.getMessage().getCode() == 200){//登录成功

                    ToastUtil.showShort(this,"登录成功");
                    startActivity(new Intent(RegisterActivity.this,MainActivity.class));

                }else if (loginBean.getMessage().getCode() == 1001){//账号或密码为空
                    ToastUtil.showShort(this,"账号或密码为空");
                }else if (loginBean.getMessage().getCode() == 201){//系统执行异常
                    ToastUtil.showShort(this,"系统执行异常");
                }else if (loginBean.getMessage().getCode() == 1004){//用户不存在
                    ToastUtil.showShort(this,"用户不存在");
                }else if (loginBean.getMessage().getCode() == 1015){//用户密码错误
                    ToastUtil.showShort(this,"用户密码错误");
                }else if (loginBean.getMessage().getCode() == 1016){//用户已被企业移除
                    ToastUtil.showShort(this,"用户已被企业移除");
                }
                break;
            case 5:
                loginBean = new Gson().fromJson(result,LoginBean.class);

                if (loginBean.getMessage().getCode() == 200){//登录成功
                    ToastUtil.showShort(this,"登录成功");
                    startActivity(new Intent(RegisterActivity.this,MainActivity.class));

                }else if (loginBean.getMessage().getCode() == 1001){//账号或密码为空
                    ToastUtil.showShort(this,"账号或密码为空");
                }else if (loginBean.getMessage().getCode() == 201){//系统执行异常
                    ToastUtil.showShort(this,"系统执行异常");
                }else if (loginBean.getMessage().getCode() == 1004){//用户不存在
                    ToastUtil.showShort(this,"用户不存在");
                }else if (loginBean.getMessage().getCode() == 1015){//用户密码错误
                    ToastUtil.showShort(this,"用户密码错误");
                }else if (loginBean.getMessage().getCode() == 1016){//用户已被企业移除
                    ToastUtil.showShort(this,"用户已被企业移除");
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onException(int requestId, String code) {

    }

    //判断输入框是否为空、空则按钮灰色不可点击、不为空则变蓝色可点击
    private void setBackground(Map<String,String> text){
        if(!TextUtils.isEmpty(text.get("1"))
                &&!TextUtils.isEmpty(text.get("2"))
                &&!TextUtils.isEmpty(text.get("3"))
                &&!TextUtils.isEmpty(text.get("4"))
                &&!TextUtils.isEmpty(text.get("5"))
                &&!TextUtils.isEmpty(text.get("6"))){
            btnRegister.setBackgroundResource(R.drawable.shape_register_pre);
        }else {
            btnRegister.setBackgroundResource(R.drawable.shape_register_nor);
        }
    }

    /**
     * 使用Handler
     * <p>
     * 静态内部类：避免内存泄漏
     */
    private static class RegisterHandler extends Handler {
        private final WeakReference<RegisterActivity> weakReference;
        public RegisterHandler(RegisterActivity activity) {
            weakReference = new WeakReference<RegisterActivity>(activity);
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            RegisterActivity activity = weakReference.get();
            if (activity != null) {
                switch (msg.what) {
                    case 0:
                        if (msg.arg1 == 0) {
                            btnVercode.setText("获取验证码");
                            btnVercode.setBackgroundColor(Color.parseColor("#689df8"));
                            btnVercode.setTextColor(Color.parseColor("#FFFFFF"));
                            btnVercode.setClickable(true);
                        } else {
                            btnVercode.setText("(" + msg.arg1 + ")秒");
                            btnVercode.setBackgroundColor(Color.parseColor("#b8bfcc"));
                            btnVercode.setClickable(false);
                        }
                        break;
                }
            }
        }
    }
    /**
     * 监听按钮下直接调用即可
     */
    private void sendMessageClick() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 59; i >= 0; i--) {
                    Message msg = myHandler.obtainMessage();
                    msg.arg1 = i;
                    myHandler.sendMessage(msg);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    class TextChange implements TextWatcher{

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            map.put("1",etEnterprise.getText().toString().trim());
            map.put("2",etName.getText().toString().trim());
            map.put("3",etPhone.getText().toString().trim());
            map.put("4",etVerification.getText().toString().trim());
            map.put("5",etPwd.getText().toString().trim());
            map.put("6",etDeterminePwd.getText().toString().trim());

            setBackground(map);
        }
        @Override
        public void afterTextChanged(Editable s) {

        }
    }
}
